<template>
  <div class="pages subcardadd">
    <div class="pageLevel">
      <!-- 表单内容 -->
      <div class="from_main">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label-width="0px">
            <el-button type="primary" size="small" @click="submitForm('ruleForm')">保 存</el-button>
            <el-button size="small" @click="resetForm('ruleForm')">取 消</el-button>
          </el-form-item>
          <p class="jichu">次卡详情</p>
          <el-form-item label="次卡名称" prop="ciname" style="margin-top:20px;">
            <el-input
              v-model="ruleForm.ciname"
              clearable
              placeholder="输入次卡名称"
              maxlength="30"
              size="small"
            ></el-input>
            <span>(4~30字)</span>
          </el-form-item>
          <el-form-item label="参与服务" prop="participation">
            <template>
              <el-button type="primary" size="small" @click="changeservice()">选择服务</el-button>
              <div class="tableMain" style="width:800px">
                <el-table
                  :data="tableDatas"
                  stripe
                  style="width: 100%"
                  class="table-service"
                  border
                >
                  <el-table-column prop="name" label="服务名称" align="center"></el-table-column>
                  <el-table-column prop="serviceTime" label="时长" align="center"></el-table-column>
                  <el-table-column prop="price" align="center" label="价格"></el-table-column>
                </el-table>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="单次服务包括的商品" label-width="150px" v-if="serviceWidthGoods.length > 0">
            <el-table
              :data="serviceWidthGoods"
              border
              style="width: 750px"
              class="table-service"
              max-height="250px"
            >
              <el-table-column label="序号" width="80" type="index" align="center"></el-table-column>
              <el-table-column prop="goodsName" label="商品名称" width="180" align="center"></el-table-column>
              <el-table-column prop="goodsCode" label="商品条码" width="180" align="center"></el-table-column>
              <el-table-column prop="primaryClassify" label="分类" align="center"></el-table-column>
              <el-table-column prop="goodsNum" label="数量" align="center" width="80"></el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="次卡次数" prop="limitofuse">
            <el-input clearable placeholder="如：20" size="small" v-model="ruleForm.limitofuse">
              <template slot="append">次</template>
            </el-input>
          </el-form-item>
          <el-form-item label="次卡会员价" prop="climoney">
            <el-input
              v-model="ruleForm.climoney"
              clearable
              placeholder="如：99.99"
              size="small"
              @keyup.native="replace(ruleForm,'climoney')"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="次卡原价" prop="originPrice">
            <el-input
              clearable
              placeholder="如：99.99"
              size="small"
              v-model="ruleForm.originPrice"
              @keyup.native="replace(ruleForm,'originPrice')"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否提成" prop="serticheng" v-if="!(soUrce !=5&&isShop==0)">
            <el-radio-group v-model="ruleForm.isCommission">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
            <template>
              <div v-show="ruleForm.isCommission === '1'">
                <el-select v-model="ruleForm.commissionType" size="small">
                  <el-option label="比例提成" value="0"></el-option>
                  <el-option label="固定提成" value="1"></el-option>
                </el-select>
                <el-input v-model="ruleForm.number" size="small"></el-input>
                <span v-if="ruleForm.commissionType == 0">%</span>
                <span v-else>元</span>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio label="0">上架</el-radio>
              <el-radio label="1">下架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="有效期" prop="termvalidity" style="margin-top:20px;">
            <el-input
              v-model="ruleForm.termvalidity"
              maxlength="8"
              clearable
              placeholder="正整数"
              size="small"
            >
              <template slot="append">个月</template>
            </el-input>
            <span>（正整数）</span>
          </el-form-item>

          <div v-if="isApp">
            <p class="jichu">购买须知</p>
            <el-form-item label="适用人数" prop="fitPerNum">
              <el-select v-model="ruleForm.fitPerNum" placeholder="请选择" size="small">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
             <span>（人数选择）</span>
            </el-form-item>

            <el-form-item label="预约信息" prop="appointmentMsg">
              <el-input clearable placeholder="" maxlength="30" size="small" v-model="ruleForm.appointmentMsg"></el-input>
              <span>(4~30字)</span>
            </el-form-item>
            <el-form-item label="规则提醒" prop="ruleHint">
              <el-input clearable placeholder="" maxlength="30" size="small" v-model="ruleForm.ruleHint"></el-input>
              <span>(4~30字)</span>
            </el-form-item>
          </div>
          <el-form-item label="除外日期" prop="checkboxGroup">
            <el-checkbox-group v-model="ruleForm.checkboxGroup" size="medium">
              <el-checkbox-button v-for="city in cities" :label="city" :key="city" style="margin-left:0px;">{{city}}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="可用时间段">
        <span>(不填写则默认为任何时间段可用)</span>
      </el-form-item>
      <el-form-item label="">
         <el-time-picker v-model="ruleForm.startTime" :default-value="defauleTime" placeholder="任意时间点" size="small" style="width: 150px" value-format="HH:mm:ss"></el-time-picker>
         <el-time-picker v-model="ruleForm.endTime" :default-value="defauleTime" placeholder="任意时间点" size="small" style="width: 150px" value-format="HH:mm:ss"></el-time-picker>
         <el-button type="primary" size="small" @click="onAddTime" :disabled="timeList.length >= 2">添加可用时间</el-button>
      </el-form-item>
      <el-form-item label="">
          <el-tag v-for="(tag,key) in timeList" :key="key" closable @close="handleClose(tag)"> {{tag.startTime}}-{{tag.endTime}}</el-tag>
      </el-form-item>
    </el-form>
      </div>
      <!-- 选择服务弹窗 -->

      <el-dialog
        title="选择服务"
        :visible.sync="dialogVisiblew"
        width="50%"
        class="addshopname shopname"
      >
        <i class="el-icon-close icon" @click="serviceicon"></i>
        <div class="prices">
          <div class="tableMain">
            <el-table :data="tableData" border style="width: 100%">
              <el-table-column label width="50">
                <template slot-scope="scope">
                  <el-radio
                    :label="scope.$index"
                    v-model="radio"
                    @change.native="handleSelectionChange2(scope.$index,scope.row)"
                  ></el-radio>
                </template>
              </el-table-column>
              <el-table-column property="name" align="center" label="服务名称"></el-table-column>
              <el-table-column property="serviceTime" align="center" label="时长"></el-table-column>
              <el-table-column property="price" align="center" label="价格"></el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer foot">
              <el-button size="small" type="primary" @click="sureservice">确 定</el-button>
              <el-button size="small" @click="cancelservice">取 消</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>


<script>
import { mapState } from "vuex";
import util from "@/util";
import { saveOrUpdatetimesCard, serviceList, serviceDetail } from "@/api";
export default {
  computed: mapState(["merchantId", "isShop", "soUrce","power"]),

  data() {
    var limitValiditydity = (rules, value, callback) => {
      // if(!value) {
      //   callback(new Error('不能输入空值'))
      // }
      if (value.length > 11) {
        callback(new Error("输入内容过长"));
      } else {
        callback();
      }
    };
    var limitPrice = (rules, value, callback) => {
      var intPart = "";
      var floatPart = "";
      var strValue = value + "";
      if (strValue.indexOf(".") > 0) {
        intPart = strValue.split(".")[0];
        floatPart = strValue.split(".")[1];
      } else {
        intPart = strValue;
      }
      if (intPart.length > 10) {
        callback(new Error("数值过大"));
      } else if (floatPart.length > 2) {
        callback(new Error("最多精确到小数点后两位"));
      } else {
        callback();
      }
    };
    return {
      radio: "",
      tableData: [],
      tableDatas: [],
      serviceWidthGoods: [], //服务需要消耗的商品
      dialogVisiblew: false,
      editorContent: "",
      ruleForm: {
        ciname: "",
        climoney: "",
        termvalidity: "",
        limitofuse: "",
        participation: "",
        sales: "0",
        salesbai: "",
        salesbai1: "",
        status: "0",
        use: "",
        classOne: "",
        classTwo: "",
        classThree: "",
        originPrice: "",
        fitPerNum: "",
        checkboxGroup: ["无"],
        appointmentMsg: "",
        ruleHint: "",
        isCommission: '0', // 是否设置提成
        commissionType: '0', //提成类型
        number: '', //提成金额或者百分比
        startTime: '',
        endTime: ''
      },
      isApp: true,
      defauleTime: new Date('0'),
      timeList: [],
      rules: {
        ciname: [
          { required: true, message: "请输入次卡名称", trigger: "blur" },
          {
            min: 4,
            max: 30,
            message: "长度在 4 到 30 个字符",
            trigger: "blur"
          },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classOne: [
          { required: true, message: "请选择所属一级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classTwo: [
          { required: true, message: "请选择所属二级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        classThree: [
          { required: true, message: "请选择所属三级分类", trigger: "change" },
          {
            validator: util.valida,
            trigger: "blur"
          }
        ],
        climoney: [
          {
            required: true,
            message: "请输入次卡会员价",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        originPrice: [
          {
            required: true,
            message: "请输入次卡原价",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          },
          {
            validator: limitPrice,
            trigger: "blur"
          }
        ],
        salesbai: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validatenum,
            trigger: "blur"
          }
        ],
        salesbai1: [
          {
            validator: util.checkSpace,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          }
        ],
        termvalidity: [
          {
            required: true,
            message: "请输入有效期",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          },
          {
            validator: limitValiditydity,
            trigger: "blur"
          }
        ],
        limitofuse: [
          {
            required: true,
            message: "请输入有效次数",
            trigger: "change"
          },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateParkingLot,
            trigger: "blur"
          },
          {
            validator: limitValiditydity,
            trigger: "blur"
          }
        ],
        participation: [
          { required: false, message: "请选择参与服务", trigger: "change" }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        fitPerNum: [
          { required: true, message: "请选择人数", trigger: "change" }
        ],
        checkboxGroup: [
          { required: true, message: "请选择日期", trigger: "change" }
        ],
        appointmentMsg: [
          { required: true, message: "请输入预约信息", trigger: "blur" },
          { min: 4, max: 30, message: "长度在 4 到 30 个字符", trigger: "blur" }
        ],
        ruleHint: [
          { required: true, message: "请输入规则提醒", trigger: "blur" },
          { min: 4, max: 30, message: "长度在 4 到 30 个字符", trigger: "blur" }
        ]
      },
      isbai: true,
      ismoney: false,
      changefuwu: [],
      options: [],
      options2: [],
      options3: [],
      fuwutiao: {},
      options: [
        { value: "0", label: "不限制" },
        { value: "1", label: "1人" },
        { value: "2", label: "2人" },
        { value: "3", label: "3人" },
        { value: "4", label: "4人" },
        { value: "5", label: "5人" },
        { value: "6", label: "6人" },
        { value: "7", label: "7人" },
        { value: "8", label: "8人" },
        { value: "9", label: "9人" },
        { value: "10", label: "10人" }
      ],
      value: "",
      cities: ["周一", "周二", "周三", "周四", "周五", "周六", "周日", "无"], //日期选择
      dayStatus: 0
    };
  },
  watch: {
    "ruleForm.checkboxGroup"(newValue, oldValue) {
      if (newValue.length > 1) {
        if (newValue[0] == "无") {
          this.ruleForm.checkboxGroup.splice(0, 1);
        } else {
          for (let i = 0; i < newValue.length; i++) {
            if (newValue[i] == "无") {
              this.ruleForm.checkboxGroup = ["无"];
            }
          }
        }
      }
    }
  },
  created() {
    this.isApp = this.setRole("APP权限")
  },
  mounted() {
  },
  methods: {
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    //字符串过滤
    replace(obj, key) {
      let that = this;
      let event = event || window.event;
      if (event.keyCode == 13) {
        setTimeout(() => {
          that.validItem(obj, key);
        }, 100);
      } else {
        that.validItem(obj, key);
      }
    },
    validItem(obj, key) {
      let res = "";
      switch (key) {
        case "salesbai":
        case "climoney":
        case "originPrice":
          res = util.replaceNum(obj[key], 10);
          break;
      }
      this.$set(obj, key, res);
    },
    //获取服务详情
    serdetail(id) {
      let data = {
        id: id
      };
      serviceDetail(data).then(res => {
        if (res.data.goodsList) {
          this.serviceWidthGoods = res.data.goodsList;
        } else {
          this.serviceWidthGoods = [];
        }
      });
    },
    // 保存
    getContent() {
      var addci = new FormData();
      addci.append("companyId", this.merchantId); //公司id
      addci.append("name", this.ruleForm.ciname); //次卡名称
      addci.append("primaryClassification", this.ruleForm.classOne);
      addci.append("secondClassification", this.ruleForm.classTwo);
      addci.append("threeClassification", this.ruleForm.classThree);
      addci.append("price", this.ruleForm.climoney); //售价会员价
      addci.append("validDay", this.ruleForm.termvalidity); //有效期
      addci.append("times", this.ruleForm.limitofuse); //使用次数
      addci.append("deductType", this.ruleForm.sales); //提成方式

      addci.append("status", this.ruleForm.status); //状态
      addci.append("serviceId", this.fuwutiao.id); //服务id
      addci.append("fitPerNum", this.ruleForm.fitPerNum); //适用人数
      addci.append("useExcludeDate", this.ruleForm.checkboxGroup);
      addci.append("appointmentMsg", this.ruleForm.appointmentMsg);
      addci.append("ruleHint", this.ruleForm.ruleHint);
      addci.append("originPrice", this.ruleForm.originPrice);
      let deductAmount;
      if (this.ruleForm.sales == 0) {
        deductAmount = this.ruleForm.salesbai;
      } else if (this.ruleForm.sales == 1) {
        deductAmount = this.ruleForm.salesbai1;
      }
      let data={
        companyId:this.merchantId,
        name:this.ruleForm.ciname,
        price:this.ruleForm.climoney,
        validDay:this.ruleForm.termvalidity,
        times:this.ruleForm.limitofuse,
        deductType:this.ruleForm.sales,
        status:this.ruleForm.status,
        serviceId:this.fuwutiao.id,
        fitPerNum:this.ruleForm.fitPerNum,
        useExcludeDate:this.ruleForm.checkboxGroup.toString(),
        appointmentMsg:this.ruleForm.appointmentMsg,
        ruleHint:this.ruleForm.ruleHint,
        originPrice:this.ruleForm.originPrice,
        timeList: this.timeList,
        royalty: this.ruleForm.isCommission,
        deductType: this.ruleForm.commissionType,
        deductAmount: this.ruleForm.number
      }

      if (this.fuwutiao.id != undefined) {
        saveOrUpdatetimesCard(data).then(res => {
          if (res.code == "200") {
            history.back();
          }

        });
      } else {
        this.$message({
          type: "error",
          message: "请选择参与服务"
        });
      }
    },
    hmsToSecondsOnly(str) {
      var p = str.split(':'),
          s = 0, m = 1;
      while (p.length > 0) {
         s += m * parseInt(p.pop(), 10);
         m *= 60;
      }
       return s;
    },

    submitForm(formName) {
      if (this.ruleForm.isCommission == '1' && (!this.ruleForm.number || this.ruleForm.number == 0)) {
        this.$message.error('请输入提成值且大于0！')
        return
      }
      if(this.timeList.length == 2) {
        const t1 = this.hmsToSecondsOnly(this.timeList[0].startTime),
              t2 = this.hmsToSecondsOnly(this.timeList[0].endTime),
              t3 = this.hmsToSecondsOnly(this.timeList[1].startTime),
              t4 = this.hmsToSecondsOnly(this.timeList[1].endTime);
        if(t4<t1||t2<t3){
	        this.$refs[formName].validate(valid => {
            if (valid) {
              if(parseFloat(this.ruleForm.climoney) > parseFloat(this.ruleForm.originPrice)){
                this.$message.error('会员价格不能大于原价格')
                return
             }
             this.getContent();
             } else {
             return false;
            }
          });
        }else{
	        this.$message.error('时间有重叠')
        }
      }else {
         this.$refs[formName].validate(valid => {
            if (valid) {
              if(parseFloat(this.ruleForm.climoney) > parseFloat(this.ruleForm.originPrice)){
                this.$message.error('会员价格不能大于原价格')
                return
             }
             this.getContent();
             } else {
             return false;
            }
          });
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      history.back();
    },
    // 营业员提成
    moneychange(val) {
      if (val == "0") {
        this.isbai = true;
        this.ismoney = false;
      } else if (val == "1") {
        this.ismoney = true;
        this.isbai = false;
      }
    },
    // 选择服务
    // 服务的列表
    changeservice() {
      this.dialogVisiblew = true;
      let data = {
        companyId: this.merchantId
      };
      serviceList(data).then(res => {
        this.tableData = res.data;
      });
    },
    // 点击×
    serviceicon() {
      this.dialogVisiblew = false;
    },
    // 点击选中
    handleSelectionChange2(index, row) {
      this.fuwutiao = row;
    },
    // 点击确定
    sureservice(id) {
      if (this.fuwutiao.id != id) {
        this.tableDatas = [];
        this.tableDatas.push(this.fuwutiao);
      }
      this.dialogVisiblew = false;
      this.serdetail(this.fuwutiao.id);
    },
    cancelservice() {
      this.dialogVisiblew = false;
    },
    // 添加可用时间
    onAddTime() {
      if(this.ruleForm.endTime && this.ruleForm.startTime){
        if(this.ruleForm.endTime < this.ruleForm.startTime) {
          this.$message.error("结束时间不能大于开始时间")
        } else {
          this.timeList.push({
            startTime: this.ruleForm.startTime,
            endTime: this.ruleForm.endTime
          })
          this.ruleForm.startTime = '';
          this.ruleForm.endTime = ''
        }
      }else {
        this.$message.error('请选择可用时间')
      }
    },
    //  删除可用时间
    handleClose(tag) {
      this.timeList.splice(this.timeList.indexOf(tag), 1);
    }
  }
};
</script>
<style scoped>
.el-tag {
  margin-right: 10px;
}
.from_main .el-input {
  width: 350px;
}
.wxclass .el-form-item {
  float: left;
}

.wxclass .el-form-item:nth-child(2) {
  margin-left: 10px;
}

.wxclass .el-form-item:nth-child(3) {
  margin-left: 10px;
}
/*表单的样式*/

.from_main {
  margin-top: 15px;
}

.from_main p {
  width: 100%;
  color: #444;
  font-size: 14px;
  border-bottom: 1px dashed #ccc;
  padding-bottom: 10px;
}

.from_main .el-input {
  width: 350px;
}

.from_main .input {
  width: 200px;
}

.from_main .line {
  margin-left: 35px;
}

.from_main .el-textarea__inner {
  width: 500px;
}

.from_main .fotter_button {
  margin-left: 350px;
}
.foot {
  margin-top: 20px;
  text-align: center;
}
</style>
<style>
#editorElem p {
  border-bottom: none !important;
}
.from_main .wxclass .el-input {
  width: 200px;
}
.shopname .el-radio__label {
  display: none;
}
.subcardadd .el-input-group--prepend .el-input__inner,
.el-input-group__append {
  border: solid 1px #579ff8;
  background-color: #579ff8;
  color: #fff;
}
.table-service th,
.table-service td {
  padding: 6px 0 !important;
}
</style>
